METHOD TOSORTED() IN JAVASCRIPT
This note explains the toSorted() method in simple language.
toSorted() sorts array elements and returns a new array, which means the original array stays unchanged. By default, it sorts in ascending order.
1. What toSorted() does
The toSorted() method is used to sort an array.
Basic syntax:
array.toSorted();
It:
- sorts the elements
- returns a new array
- does not change the original array
Diagram 1. Main idea
Original array
↓
toSorted()
↓
new sorted array
Original array stays the same
This is the first important thing to remember:
toSorted() does not rewrite the old array
It creates a new one.
2. Example with numbers
const scores = [61, 19, 74, 35, 92, 56];
const ascendingScores = scores.toSorted();
console.log(scores); // [61, 19, 74, 35, 92, 56]
console.log(ascendingScores); // [19, 35, 56, 61, 74, 92]
Diagram 2. Before and after sorting
scores
[61, 19, 74, 35, 92, 56]
toSorted()
↓
ascendingScores
[19, 35, 56, 61, 74, 92]
scores is still:
[61, 19, 74, 35, 92, 56]
ascendingScores is the new sorted array. scores does not change.
3. Important warning about numbers
By default, toSorted() converts elements to strings before sorting. That means numbers are compared like text, not like true numeric values.
Example:
const scores = [27, 2, 41, 4, 7, 3, 75];
console.log(scores.toSorted()); // [2, 27, 3, 4, 41, 7, 75]
This result may look strange if you expect normal number sorting.
Diagram 3. Why default number sorting can look strange
Numbers:
[27, 2, 41, 4, 7, 3, 75]
Default toSorted()
↓
treats numbers like strings
Compare:
"2"
"27"
"3"
"4"
"41"
"7"
"75"
Result:
[2, 27, 3, 4, 41, 7, 75]
JavaScript compares them character by character:
"2"comes before"27""27"comes before"3"
So default sorting is not always good for numbers.
4. Array of strings
With strings, default sorting is alphabetic.
Example:
const students = ["Jacob", "Rachel", "Solomon", "Noah", "Ezra", "Miriam"];
console.log(students.toSorted());
// ["Noah", "Rachel", "Miriam", "Jacob", "Ezra", "Solomon"]
Diagram 4. Default string sorting
Original:
["Jacob", "Rachel", "Solomon", "Noah", "Ezra", "Miriam"]
Sorted:
["Noah", "Rachel", "Miriam", "Jacob", "Ezra", "Solomon"]
For strings, default toSorted() is usually easier to understand because it sorts alphabetically.
5. Uppercase and lowercase letters
Uppercase and lowercase letters do not have the same code values. That is why the result can look like this:
const letters = ["b", "B", "a", "A", "c", "C"];
console.log(letters.toSorted()); // ["A", "B", "C", "a", "b", "c"]
Diagram 5. Letter sorting
Original:
["b", "B", "a", "A", "c", "C"]
Sorted:
["A", "B", "C", "a", "b", "c"]
Uppercase letters come before lowercase letters in this default sort order.
6. Your own sorting order
If default sorting is not enough, you can pass a callback function to toSorted(). This callback is called a comparison function.
Basic syntax:
array.toSorted((a, b) => {
// compare a and b
});
Where:
ais the first valuebis the second value
Diagram 6. Comparison function idea
toSorted((a, b) => ...)
↓
JavaScript compares two values
↓
callback decides their order
Now you control how sorting works.
7. Numeric sorting in ascending order
To sort numbers correctly in ascending order, use:
(a, b) => a - b
Example:
const scores = [61, 19, 74, 35, 92, 56];
const ascendingScores = scores.toSorted((a, b) => a - b);
console.log(ascendingScores); // [19, 35, 56, 61, 74, 92]
Diagram 7. Ascending number sort
Compare a and b
↓
a - b
If result is negative:
a goes before b
This creates the normal numeric ascending order people usually expect.
8. Numeric sorting in descending order
To sort numbers in descending order, use:
(a, b) => b - a
Example:
const scores = [61, 19, 74, 35, 92, 56];
const descendingScores = scores.toSorted((a, b) => b - a);
console.log(descendingScores); // [92, 74, 61, 56, 35, 19]
Diagram 8. Descending number sort
Compare a and b
↓
b - a
If result is positive for bigger second value:
b goes before a
This gives the highest number first.
9. What negative, positive, and zero mean
The comparison function result has a meaning:
- negative value →
agoes beforeb - positive value →
bgoes beforea - zero → keep their relative order unchanged
Diagram 9. Compare function rules
Result < 0 → a before b
Result > 0 → b before a
Result = 0 → keep order
This rule is the key to understanding custom sorting.
10. String sorting with localeCompare()
For strings, custom sorting is usually done with localeCompare().
Syntax:
firstString.localeCompare(secondString)
It returns:
- negative value if first string should come first
- positive value if second string should come first
- zero if they are equal
Diagram 10. localeCompare() logic
"a".localeCompare("b") → negative
"b".localeCompare("a") → positive
"a".localeCompare("a") → 0
This fits perfectly with what toSorted() needs.
11. String sorting in alphabetical order
Example:
const students = ["Jacob", "Rachel", "Solomon", "Noah", "Ezra", "Miriam"];
const inAlphabetOrder = students.toSorted((a, b) => a.localeCompare(b));
console.log(inAlphabetOrder);
// ["Noah", "Rachel", "Miriam", "Jacob", "Ezra", "Solomon"]
Diagram 11. Alphabetical string sorting
toSorted((a, b) => a.localeCompare(b))
↓
A to Z order
This is the standard way to sort strings alphabetically.
12. Reverse string sorting
Example:
const students = ["Jacob", "Rachel", "Solomon", "Noah", "Ezra", "Miriam"];
const inReversedOrder = students.toSorted((a, b) => b.localeCompare(a));
console.log(inReversedOrder);
// ["Solomon", "Ezra", "Jacob", "Miriam", "Rachel", "Noah"]
Diagram 12. Reverse string sorting
toSorted((a, b) => b.localeCompare(a))
↓
Z to A order
This is just the reverse comparison.
13. Sorting objects
When you sort an array of objects, you usually sort by one property.
Example tasks:
- sort by score
- sort by price
- sort by age
- sort by name
Example:
const students = [
{ name: "Aaron", score: 83 },
{ name: "Benjamin", score: 59 },
{ name: "Samuel", score: 37 },
{ name: "David", score: 94 },
];
const inAscendingScoreOrder = students.toSorted(
(firstStudent, secondStudent) => firstStudent.score - secondStudent.score
);
const inDescendingScoreOrder = students.toSorted(
(firstStudent, secondStudent) => secondStudent.score - firstStudent.score
);
const inAlphabeticalOrder = students.toSorted((firstStudent, secondStudent) =>
firstStudent.name.localeCompare(secondStudent.name)
);
Diagram 13. Sorting objects by property
students
│
├─ { name: "Aaron", score: 83 }
├─ { name: "Benjamin", score: 59 }
├─ { name: "Samuel", score: 37 }
└─ { name: "David", score: 94 }
Sort by:
- score ascending
- score descending
- name alphabetically
When sorting objects, the callback usually compares one property.
14. Method chains
A method chain means calling one method after another. Each next method works on the result of the previous one.
Example:
const students = [
{ name: "Aaron", score: 83, courses: ["mathematics", "physics"] },
{ name: "Benjamin", score: 59, courses: ["science", "mathematics"] },
{ name: "Samuel", score: 37, courses: ["physics", "biology"] },
{ name: "David", score: 94, courses: ["literature", "science"] },
];
const names = students
.toSorted((a, b) => a.score - b.score)
.map(student => student.name);
console.log(names); // ["Samuel", "Benjamin", "Aaron", "David"]
Diagram 14. Method chain
students
↓ toSorted(...)
sorted students
↓ map(...)
names array
Instead of saving an extra intermediate variable, we connect the methods directly.
15. Another chain example
Example:
const students = [
{ name: "Aaron", score: 83, courses: ["mathematics", "physics"] },
{ name: "Benjamin", score: 59, courses: ["science", "mathematics"] },
{ name: "Samuel", score: 37, courses: ["physics", "biology"] },
{ name: "David", score: 94, courses: ["literature", "science"] },
];
const uniqueSortedCourses = students
.flatMap(student => student.courses)
.filter((course, index, array) => array.indexOf(course) === index)
.toSorted((a, b) => a.localeCompare(b));
console.log(uniqueSortedCourses);
Diagram 15. Long chain step by step
students
↓ flatMap()
all courses
↓ filter()
unique courses
↓ toSorted()
alphabetically sorted unique courses
This is a good example of how methods can work together.
16. Important note about long chains
Method chains are useful, but they should usually stay short.
Why?
- each method call means another pass through the array
- very long chains can affect performance
- shorter chains are easier to read
Diagram 16. Chain balance
Short chain
↓
clean and useful
Too many methods
↓
harder to read
may affect performance
In practice, 2 or 3 chained methods are common.
17. Common beginner mistakes
Mistake 1. Thinking toSorted() changes the original array.
It does not. It returns a new array.
Mistake 2. Expecting default number sorting to always be numeric.
Without a comparison callback, numbers are compared like strings.
Mistake 3. Forgetting to use localeCompare() for strings.
For custom string sorting, localeCompare() is usually the right tool.
Mistake 4. Forgetting to compare object properties.
When sorting objects, compare the needed property, not the whole object.
Diagram 17. Common mistakes summary
1. toSorted() returns a new array
2. default number sorting can be string-based
3. use localeCompare() for string sorting
4. sort objects by property
18. Practical examples
Example 1. Correct numeric ascending sort
const numbers = [10, 2, 30, 4];
const sorted = numbers.toSorted((a, b) => a - b);
console.log(sorted); // [2, 4, 10, 30]
Example 2. Correct numeric descending sort
const numbers = [10, 2, 30, 4];
const sorted = numbers.toSorted((a, b) => b - a);
console.log(sorted); // [30, 10, 4, 2]
Example 3. Sort names alphabetically
const names = ["Isaac", "Sarah", "Nikita"];
const sortedNames = names.toSorted((a, b) => a.localeCompare(b));
console.log(sortedNames); // ["Sarah", "Isaac", "Nikita"]
Example 4. Sort products by price
const products = [
{ name: "Phone", price: 500 },
{ name: "Laptop", price: 1200 },
{ name: "Tablet", price: 700 },
];
const sortedByPrice = products.toSorted((a, b) => a.price - b.price);
console.log(sortedByPrice);
19. Quick summary
toSorted() sorts an array and returns a new array.
By default, elements are sorted in ascending order.
For numbers, use (a, b) => a - b for numeric ascending sort.
For descending numbers, use (a, b) => b - a.
For strings, use localeCompare().
For objects, sort by comparing one property.
Diagram 18. Final map
toSorted()
│
├─ returns new array
├─ original stays unchanged
├─ default sort
├─ custom numeric sort
├─ custom string sort
├─ object sorting
└─ method chains
20. Easy memory rules
toSorted() = new sorted array
a - b = ascending numbers
b - a = descending numbers
localeCompare() = string sorting
21. Revision block
toSorted()returns a new arraytoSorted()does not change the original array- Default number sorting may behave like string sorting
- Use
(a, b) => a - bfor correct numeric ascending order - Use
(a, b) => b - afor correct numeric descending order - Use
localeCompare()for strings - Arrays of objects are sorted by comparing one property
toSorted()can be used in method chains
22. Final conclusion
toSorted() is a very useful modern array method.
If you understand:
- that it returns a new array
- that the original array stays unchanged
- how default sorting works
- how to sort numbers correctly
- how to sort strings with
localeCompare() - how to sort objects by property
- how it works in method chains
then you already have a strong base for using sorting in JavaScript.
This method is very useful in real projects with users, products, students, scores, names, and API data.